package com.navcoo.yidaaddproapi.service.serviceImpl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.navcoo.yidaaddproapi.constants.StatusConstants;
import com.navcoo.yidaaddproapi.mapper.UserMapper;
import com.navcoo.yidaaddproapi.pojo.dao.UserDAO;
import com.navcoo.yidaaddproapi.service.LoginService;
import com.navcoo.yidaaddproapi.utils.DESUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 登录服务Impl
 *
 * @author Navcoo
 * @date 2024-04-28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final UserMapper userMapper;

    @Value("${encrypt-key}")
    private String encryptKey;

    /**
     * 登录
     *
     * @param password  密码
     * @param authLogin 身份验证登录
     * @param userEmail 用户电子邮件
     * @return {@link SaResult}
     */
    @Override
    public SaResult doLogin(String userEmail, String password, Boolean authLogin) {

        // 构建查询条件
        QueryWrapper<UserDAO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserDAO::getUserEmail, userEmail);
        queryWrapper.lambda().eq(UserDAO::getStatus, StatusConstants.NORMAL);

        // 查询用户信息
        UserDAO user = userMapper.selectOne(queryWrapper);
        log.info("user:{}", user);

        if (ObjectUtil.isEmpty(user)) {
            log.error("当前用户不存在");
            return SaResult.error("当前用户不存在");
        } else {
            if (StrUtil.equals(DESUtil.decrypt(user.getPasswordEncrypt(), encryptKey), password)) {
                // 会话登录：参数填写要登录的账号id，建议的数据类型：long | int | String， 不可以传入复杂类型，如：User、Admin 等等
                StpUtil.login(user.getUserId(), authLogin);
                // 获取当前登录的用户信息
                SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
                log.info("tokenInfo:{}", tokenInfo);
                // 返回登录成功
                return SaResult.data(tokenInfo);
            }
            log.error("密码错误");
            return SaResult.error("密码错误");
        }

    }


    /**
     * 注销
     *
     * @param token 令牌
     * @return {@link SaResult}
     */
    @Override
    public SaResult loginOut(String token) {
        StpUtil.logout(token);
        return SaResult.ok("注销成功！");
    }

    /**
     * 查询是否登录
     *
     * @param token 令牌
     * @return {@link SaResult}
     */
    @Override
    public SaResult isLogin(String token) {
        boolean isLogin = ObjectUtil.isNotNull(StpUtil.getLoginIdByToken(token));
        return SaResult.data(isLogin);
    }
}
